package com.dale.ws;

import cn.hutool.Hutool;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import com.dale.entity.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import sun.misc.MessageUtils;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;

//因为我是前后端分离 所以拿不到session
//@ServerEndpoint(value = "/chat", configurator = GetHttpSessionConfigurator.class)
@ServerEndpoint(value = "/chat")
@Component
@Slf4j
public class ChatEndPoint {


    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<ChatEndPoint> webSocketSet = new CopyOnWriteArraySet<ChatEndPoint>();

    private Session session;

    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 向客户端发送消息
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {


        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();
        log.info("有新连接加入！当前在线人数为" + getOnlineCount());
        SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm:ss");//设置日期格式
        try {
            String s = objectMapper.writeValueAsString(new Message("系统消息", "有新连接加入 当前用户数为:" + getOnlineCount(),df.format(new Date())));
            sendMessage(s);

        } catch (IOException e) {
            System.out.println("websocket IO异常");
        }
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息:" + message);

        //群发消息
        for (ChatEndPoint item : webSocketSet) {
            try {
                Message msg = objectMapper.readValue(message, Message.class);
                String s = objectMapper.writeValueAsString(msg);
                item.sendMessage(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static synchronized void addOnlineCount() {
        ChatEndPoint.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        ChatEndPoint.onlineCount--;
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }


}
